package com.easyadmin.pro.tool;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * packageName com.easyadmin.pro.tool
 *
 * @author 骑着蚂蚁去上天
 * @version JDK 17
 * @className RedisUtils
 * @date 2024/8/19
 * @description Redis 工具
 */
@Slf4j
public class RedisUtils {

    /**
     * 缓存设置数据
     * @param redisKey
     * @param value
     */
    public static void setValue(String redisKey, Object value) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(value));
    }

    /**
     * 删除缓存数据
     * @param redisKey
     */
    public static void removeData(String redisKey) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.delete(redisKey);
    }

    /**
     * 获取缓存数据
     * @param redisKey
     * @return
     */
    public static Object getValue(String redisKey) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        return redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 设置缓存有过期时间
     * @param redisKey
     * @param value
     * @param timeOut
     * @param timeUnitType
     */
    public static void setValueValidityPeriod(String redisKey, Object value, long timeOut, String timeUnitType) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.opsForValue().set(redisKey, value,timeOut, TimeUnit.valueOf(timeUnitType));
    }

    /**
     * 获取HASH缓存数据
     * @param redisKey
     * @return
     */
    public static Object getHash(String redisKey) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        Map entries = redisTemplate.opsForHash().entries(redisKey);
        return entries;
    }

    /**
     * 设置HASH缓存数据
     * @param redisKey
     * @param value
     */
    public static void setHash(String redisKey, Object value) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.opsForHash().putAll(redisKey, (Map) value);
    }

    /**
     * 刷新obj缓存
     * @param redisKey
     * @param value
     */
    public static void refreshObj(String redisKey, Object value) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.opsForValue().set(redisKey, value);
    }

    /**
     * 刷新map缓存
     * @param redisKey
     * @param value
     */
    public static void refreshMap(String redisKey, Object value) {
        RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
        redisTemplate.opsForHash().putAll(redisKey, (Map) value);
    }
}